package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductAttrTypeConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationServiceImpl attrAttrgroupRelationService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //1.自己的表保存
        this.save(attrEntity);
       if( attr.getAttrType() == ProductAttrTypeConstant.ProductAttrType.ATTR_BASE.getCode()){
           //2.attr_group_attr 关联表保存
           AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
           attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
           attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
           attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
       }

    }
    @Transactional
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId,String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equals(type)? ProductAttrTypeConstant.ProductAttrType.ATTR_BASE.getCode():ProductAttrTypeConstant.ProductAttrType.ATTR_SALE.getCode());
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)){
            wrapper.and((wrapper1)->{
                wrapper1.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page=null;
        //如果传入了分类id，就进行分类查询，否则就查询全部
       if (catelogId==0){
            page= this.page(
                   new Query<AttrEntity>().getPage(params),
                   wrapper
           );
       }else {
           wrapper.eq("catelog_id", catelogId);
           page = this.page(
                   new Query<AttrEntity>().getPage(params),
                   wrapper
           );
       }
        PageUtils pageUtils = new PageUtils(page);
        //获取所有数据 再封装成AttrRespVo返回
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> collect = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
           if ("base".equals(type)){
               AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationService.getById(attrEntity.getAttrId());

               if (attrAttrgroupRelation != null) {
                   AttrGroupEntity groupEntity = attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId());
                   if (groupEntity!=null){attrRespVo.setGroupName(groupEntity.getAttrGroupName());}
               }
           }
            return attrRespVo;
        }).collect(Collectors.toList());

       pageUtils.setList(collect);
       return pageUtils;
    }
    @Transactional
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //基础属性才有分组信息
        if(attrEntity.getAttrType()==ProductAttrTypeConstant.ProductAttrType.ATTR_BASE.getCode()){
            AttrAttrgroupRelationEntity relation= attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
           if(relation!=null){
               AttrGroupEntity groupEntity = attrGroupDao.selectById(relation.getAttrGroupId());
               if (groupEntity!=null){
                   attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                   attrRespVo.setAttrGroupId(groupEntity.getAttrGroupId());
               }
           }
        }
        Long[] path = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(path);
        return attrRespVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        // 基础属性才有分组信息
        if(attrEntity.getAttrType()==ProductAttrTypeConstant.ProductAttrType.ATTR_BASE.getCode()){
            //更新关联表
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            //如果销售属性变为基础属性，没有分组id传过来，则不更新
            if (attr.getAttrGroupId()!=null){
                attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            }
        }
    }

}